package com.xiaowu.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowu.common.core.constants.CacheConstants;
import com.xiaowu.common.core.constants.Constants;
import com.xiaowu.common.core.constants.HttpConstants;
import com.xiaowu.common.core.domain.LoginUser;
import com.xiaowu.common.core.domain.R;
import com.xiaowu.common.core.domain.vo.LoginUserVO;
import com.xiaowu.common.core.enums.ResultCode;
import com.xiaowu.common.core.enums.UserIdentity;
import com.xiaowu.common.core.enums.UserStatus;
import com.xiaowu.common.core.utils.ThreadLocalUtil;
import com.xiaowu.common.message.service.AliSmsService;
import com.xiaowu.common.redis.service.RedisService;
import com.xiaowu.common.security.exception.ServiceException;
import com.xiaowu.common.security.service.TokenService;
import com.xiaowu.friend.domain.user.User;
import com.xiaowu.friend.domain.user.dto.UserDTO;
import com.xiaowu.friend.domain.user.dto.UserUpdateDTO;
import com.xiaowu.friend.domain.user.vo.UserVO;
import com.xiaowu.friend.manager.UserCacheManager;
import com.xiaowu.friend.mapper.user.UserMapper;
import com.xiaowu.friend.service.user.IUserService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

@Service
public class UserServiceImpl implements IUserService {

    //注入阿里短信服务
    @Autowired
    AliSmsService aliSmsService;

    //注入Redis服务
    @Autowired
    RedisService redisService;

    //注入用户Mapper
    @Autowired
    UserMapper userMapper;

    //注入Token服务
    @Autowired
    TokenService tokenService;

    //注入用户缓存管理器
    @Autowired
    UserCacheManager userCacheManager;


    //短信验证码过期时间，默认为5分钟
    @Value("${sms.code-expiration:5}")
    private Long phoneCodeExpiration;

    //短信验证码发送次数限制，默认为3次
    @Value("${sms.send-limit:3}")
    private Integer sendLimit;

    //是否发送短信验证码，默认为false
    @Value("${sms.is-send:false}")
    private boolean isSend;

    //JWT密钥
    @Value("${jwt.secret}")
    private String secret;

    @Value("${file.oss.downloadUrl}")
    private String downloadUrl;

    @Override
    public boolean sendCode(UserDTO userDTO) {
        //检查手机号是否合法
        if (!checkPhone(userDTO.getPhone())) {
            throw new ServiceException(ResultCode.FAILED_USER_PHONE);
        }
        //获取手机号对应的验证码缓存key
        String phoneCodeKey = getPhoneCodeKey(userDTO.getPhone());
        //获取手机号对应的验证码缓存过期时间
        Long expire = redisService.getExpire(phoneCodeKey, TimeUnit.SECONDS);
        //如果缓存存在且距离过期时间不足60秒，则抛出异常
        if (expire != null&& (phoneCodeExpiration * 60 - expire) < 60) {
            throw new ServiceException(ResultCode.FAILED_FREQUENT);
        }
        //限制每天验证码发送次数
        String codeTimeKey = getCodeTimeKey(userDTO.getPhone());
        Long sendTimes = redisService.getCacheObject(codeTimeKey, Long.class);
        //如果发送次数超过限制，则抛出异常
        if (sendTimes != null&& sendTimes > sendLimit) {
            throw new ServiceException(ResultCode.FAILED_TIME_LIMIT);
        }

        //生成验证码
        String code = isSend?RandomUtil.randomNumbers(6) : Constants.DEFAULT_CODE;
        //发送验证码
        aliSmsService.sendMobileCode(userDTO.getPhone(), code);
        //缓存验证码到redis
        redisService.setCacheObject(phoneCodeKey, code, phoneCodeExpiration, TimeUnit.MINUTES);
        if (isSend) {
            boolean sendMobileCode = aliSmsService.sendMobileCode(userDTO.getPhone(), code);
            if (!sendMobileCode) {
                throw new ServiceException(ResultCode.FAILED_SEND_CODE);
            }
        }
        //增加发送次数
        redisService.increment(codeTimeKey);
        if (sendTimes == null) { //说明是当天第一次发送验证码
            long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(),
                    LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0)
                            .withNano(0));
            redisService.expire(codeTimeKey, seconds, TimeUnit.SECONDS);
        }
        return true;
    }

    @Override
    public String codeLogin(UserDTO userDTO) {
        //验证验证码
        checkCode(userDTO);
        //根据手机号查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, userDTO.getPhone()));
        if (user == null) {
            //注册逻辑
            user = new User();
            user.setPhone(userDTO.getPhone());
            user.setStatus(UserStatus.Normal.getValue());
            user.setCreateBy(Constants.SYSTEM_USER_ID);
            userMapper.insert(user);
        }
        //生成token
        return tokenService.createToken(user.getUserId(), secret,
                UserIdentity.ORDINARY.getValue(), user.getNickName(), user.getHeadImage());
    }

    @Override
    public boolean logout(String token) {
        //处理token前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        //删除登录用户
        return tokenService.deleteLoginUser(token, secret);
    }

    @Override
    public R<LoginUserVO> info(String token) {
        //处理token前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        //获取登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        if (loginUser == null) {
            return R.fail();
        }
        //封装返回结果
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        loginUserVO.setHeadImage(downloadUrl + loginUser.getHeadImage());
        return R.ok(loginUserVO);
    }

    @Override
    public UserVO detail() {
        //获取当前用户ID
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        if (userId == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //根据用户ID获取用户信息
        UserVO userVO = userCacheManager.getUserById(userId);
        if (userVO == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if (StrUtil.isNotEmpty(userVO.getHeadImage())) {
            userVO.setHeadImage(downloadUrl + userVO.getHeadImage());
        }
        return userVO;
    }

    @Override
    public int edit(UserUpdateDTO userUpdateDTO) {
        //获取当前用户
        User user = getUser();
        //复制更新信息
        BeanUtil.copyProperties(userUpdateDTO, user);
        //刷新用户缓存
        refreshUserCache(user);
        return userMapper.updateById(user);
    }

    @Override
    public int updateHeadImage(String headImage) {
        //获取当前用户
        User user = getUser();
        //更新头像
        user.setHeadImage(headImage);
        //刷新用户缓存
        refreshUserCache(user);
        return userMapper.updateById(user);
    }

    //刷新用户缓存
    private void refreshUserCache(User user) {
        userCacheManager.refreshUser(user);
        tokenService.refreshLoginUser(user.getNickName(), user.getHeadImage(),
                ThreadLocalUtil.get(Constants.USER_KEY, String.class));
    }

    //获取当前用户
    @NotNull
    private User getUser() {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        if (userId == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return user;
    }

    //验证验证码
    private void checkCode(UserDTO userDTO) {
        String phoneCodeKey = getPhoneCodeKey(userDTO.getPhone());
        String cacheCode = redisService.getCacheObject(phoneCodeKey, String.class);
        if (StrUtil.isEmpty(cacheCode)) {
            throw new ServiceException(ResultCode.FAILED_INVALID_CODE);
        }
        if (!userDTO.getCode().equals(cacheCode)){
            throw new ServiceException(ResultCode.FAILED_ERROR_CODE);
        }
        //验证码比对成功
        redisService.deleteObject(phoneCodeKey);
    }

    //获取手机号对应的验证码缓存key
    private String getCodeTimeKey(String phone) {
        return CacheConstants.CODE_TIME_KEY + phone;
    }

    //获取手机号对应的验证码缓存key
    private String getPhoneCodeKey(String phone) {
        return CacheConstants.PHONE_CODE_KEY + phone;
    }

    //检查手机号是否合法
    public static boolean checkPhone(String phone) {
        Pattern regex = Pattern.compile("^1[2|3|4|5|6|7|8|9][0-9]\\d{8}$");
        Matcher m = regex.matcher(phone);
        return m.matches();
    }
}
